#include <iostream>
#include <string>
#include <stdio.h>
#include <set>

#include "Log.hpp"

const std::string sep = " ";

class ComExcute
{
private:
    void LoadConf(const std::string &conf)
    {
        std::ifstream in(conf);
        if (!in.is_open())
        {
            LOG(FATAL, "open conf file failed ! \n");
            return;
        }
        std::string line;
        while (getline(in, line))
        {
            LOG(DEBUG, "load command [%s] success\n", line.c_str());
            _safe_cmd.insert(line);
        }
        in.close();
    }

public:
    ComExcute(std::string cond_path) : _cond_path(cond_path)
    {
        LoadConf(_cond_path);
    }

    std::string PrefixCommand(const std::string &cmd)
    {
        if (cmd.empty())
            return std::string();

        auto pos = cmd.find(sep);

        //？？？？？？？？？？？？？？？？？？？
        if (pos == std::string::npos)
            return cmd;

        return cmd.substr(0, pos);
    }

    bool SafeCheck(const std::string &cmd)
    {
        std::string prefix = PrefixCommand(cmd);
        auto iter = _safe_cmd.find(prefix);
        if (iter == _safe_cmd.end())
        {
            LOG(DEBUG, "未找到\n");
            return false;
        }
        return true;
    }

    std::string Excute(std::string req)
    {
        std::string rsp;
        if (SafeCheck(req))
        {
            FILE *fp = popen(req.c_str(), "r");
            if (fp == nullptr)
            {
                LOG(WARNING, "create file failed! \n");
                return std::string("failed");
            }

            //？？？？？？？？？？？？？？？？？？？
            char buffer[1024];
            LOG(DEBUG ,"文件打开成功");
            while (fgets(buffer, sizeof(buffer) - 1, fp) != NULL)
            {
                rsp += buffer;
            }
            pclose(fp);
        }

        else
        {
            return "坏坏";
        }

        return rsp;
    }

    ~ComExcute() {}

private:
    std::set<std::string> _safe_cmd;
    std::string _cond_path;
};